package com.lp.sys.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.iframework.commons.domain.enums.HttpStatusCode;
import org.iframework.commons.domain.enums.RecordStatus;
import org.iframework.commons.domain.order.Order;
import org.iframework.commons.domain.order.OrderImpl;
import org.iframework.commons.domain.order.OrderSort;
import org.iframework.commons.domain.pager.Pager;
import org.iframework.commons.util.fast.L;
import org.iframework.commons.util.fast.V;
import org.iframework.support.spring.hibernate.service.BaseServiceSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.lp.business.domain.JsonResultModel;
import com.lp.business.model.Access;
import com.lp.business.model.Menu;
import com.lp.business.model.Role;
import com.lp.business.model.RolesUsers;
import com.lp.business.service.AccessService;
import com.lp.business.service.MenuService;
import com.lp.business.service.RoleService;
import com.lp.sys.controller.base.BaseController;
/**
 * 角色控制器
 * 
 * @author lipeng
 *
 */
@Controller
@RequestMapping("/admin/role")
public class RoleController extends BaseController<Role, String> {
	
	@Autowired
	private MenuService menuService;
	@Autowired
	private AccessService accessService;
	
	@Resource(name = "roleService")
	@Override
	public void setBaseServiceSupport(BaseServiceSupport<Role, String> baseService) {
		super.setBaseServiceSupport(baseService);
	}
	/**
	 * 加载分页列表数据
	 */
	@RequestMapping(value = "list", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView list(HttpServletRequest request,HttpServletResponse response, Role model) {
		ModelAndView modelAndView = new ModelAndView("/role/pageList");
		model.setStatus(RecordStatus.AVAILABLE);
		Pager pager = this.getPager(request);
		Order order = this.getOrder(request);
		List<Role> models = this.baseService.findByModel(model, order, pager);
		modelAndView.addObject("models", models);
		modelAndView.addObject("page", pager);

		return modelAndView;
	}

	/**
	 * 进行保存操作
	 */
	@RequestMapping(value = "save", method = { RequestMethod.POST, RequestMethod.GET })
	public void save(HttpServletRequest request, HttpServletResponse response, Role model) {

		String upId = request.getParameter("roleLookup.id");
		if (upId != null && !"".equals(upId)) {
			model.setRoleId(upId);
			model.setLevel(1);
		} else {
			model.setRoleId(null);
			model.setLevel(0);
		}
		try {
			if (V.isNotEmpty(this.baseService.save(model))) {
				renderJson(new JsonResultModel(HttpStatusCode.SUCCESS.getDesc(), "新建保存操作成功").toSysJsonString(), response);
				return;
			} else {
				renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "新建保存操作失败").toSysJsonString(), response);
				return;
			}
		} catch (Exception e) {
			L.e(e.getMessage(), e);
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "系统繁忙，请稍候再试").toSysJsonString(), response);
			return;
		}
	}

	/**
	 * 进行更新操作
	 */
	@RequestMapping(value = "update", method = { RequestMethod.POST, RequestMethod.GET })
	public void update(HttpServletRequest request, HttpServletResponse response, Role model) {
		//校验是否传入id信息
		if (V.isEmpty(model.getId())) {
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "ID必须填写").toSysJsonString(), response);
			return;
		}
		//校验是否存在相应数据
		Role menu =  this.baseService.get(model.getId());
		if (V.isEmpty(menu)) {
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "找不到需要更新的数据").toSysJsonString(), response);
			return;
		}
		//执行更新逻辑
		String upId = request.getParameter("objectLookup.id");
		if (upId != null && !"".equals(upId)) {
			model.setRoleId(upId);
			model.setLevel(1);
		} else {
			model.setRoleId(null);
			model.setLevel(0);
		}
		try {
			if (this.baseService.update(model)) {
				renderJson(new JsonResultModel(HttpStatusCode.SUCCESS.getDesc(), "更新修改操作成功").toSysJsonString(), response);
				return;
			} else {
				renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "更新修改操作失败").toSysJsonString(), response);
				return;
			}
		} catch (Exception e) {
			L.e(e.getMessage(), e);
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "系统繁忙，请稍候再试").toSysJsonString(), response);
			return;
		}
	}

	/**
	 * 进行批量删除操作
	 */
	@RequestMapping(value = "batchDelete", method = { RequestMethod.POST, RequestMethod.GET })
	public void batchDelete(HttpServletRequest request, HttpServletResponse response) {
		//1.执行必填校验
		String[] ids = request.getParameterValues("ids[]");
		if (V.isEmpty(ids)) {
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "请选择需要删除的信息").toSysJsonString(), response);
			return;
		}
		//2.执行删除
		try {
			Collection<Role> models = new ArrayList<Role>();
			for (String id : ids) {
				//校验是否有此id的数据
				Role model = this.baseService.get(id);
				if(V.isEmpty(model)){
					renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "删除失败，未找到需要删除的数据").toSysJsonString(), response);
					return;
				}
				models.add(model);
			}
			if(this.baseService.deleteAllVirtual(models)){
				renderJson(new JsonResultModel(HttpStatusCode.SUCCESS.getDesc(), "批量删除操作成功").toSysJsonString(), response);
				return;
			} else {
				renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "批量删除操作失败").toSysJsonString(), response);
				return;
			}
		} catch (Exception e) {
			L.e(e.getMessage(), e);
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "系统繁忙，请稍候再试。").toSysJsonString(), response);
			return;
		}
	}
	
	/**
	 * 角色操作
	 */
	@RequestMapping(value = "roleOperator", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView roleOperator(HttpServletRequest request, Role model) {
		//角色权限设置
		ModelAndView modelAndView = new ModelAndView("/role/roleOperator");
		//获取所有角色
		Role searchRoleModel = new Role();
		searchRoleModel.setStatus(RecordStatus.AVAILABLE);
		List<Role> roles = this.baseService.findByModel(searchRoleModel, null, null);
		modelAndView.addObject("roles", roles);
		String roleId = model.getId();
		if (V.isEmpty(roleId)) {
			roleId = roles.get(0).getId();
		}
		if (roleId != null && !"".equals(roleId)) {
			Role role = this.baseService.get(roleId);
			modelAndView.addObject("role", role);
			// 1.获取所有菜单列表，构建菜单及支持方法树
			Menu menu = new Menu();
			menu.setStatus(RecordStatus.AVAILABLE);
			List<Menu> menus = this.menuService.findByModel(menu, new OrderImpl("sort", OrderSort.ASC), null);
			modelAndView.addObject("menus", menus);
//			// 1.获取所有菜单方法列表，构建菜单及支持方法树
//			MenuMethod menuMethod = new MenuMethod();
//			List<MenuMethod> menuMethods = this.menuMethodService.findByModel(menuMethod, order, null);
//			modelAndView.addObject("menuMethods", menuMethods);
			// 2.如果有角色Id传递则把角色所拥有的权限都查询出来
			Access access = new Access();
			access.setRoleId(roleId);
			access.setStatus(RecordStatus.AVAILABLE);
			List<Access> accesses = this.accessService.findByModel(access, null, null);
			modelAndView.addObject("accesses", accesses);
		}
		
		return modelAndView;

	}

	/**
	 * 显示角色用户列表页面
	 */
	@RequestMapping(value = "roleUserAdd", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView roleUserAdd(HttpServletRequest request, HttpServletResponse response,  Role model) {
		ModelAndView modelAndView = new ModelAndView("/role/roleUserAdd");
		String roleId = request.getParameter("roleId");
		Role role = this.baseService.get(roleId);
		modelAndView.addObject("role", role);
		return modelAndView;
	}
	
	/**
	 * 显示角色用户列表页面
	 */
	@RequestMapping(value = "roleUser", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView roleUser(HttpServletRequest request, HttpServletResponse response,  Role model) {
		ModelAndView modelAndView = new ModelAndView("/role/roleUser");
		//获取所有角色
		List<Role> roles = this.baseService.findByModel(null, null, null);
		modelAndView.addObject("roles", roles);
		String roleId = model.getId();
		if (V.isEmpty(roleId)) {
			roleId = roles.get(0).getId();
		}
		if (V.isNotEmpty(roleId)) {
			Role role = this.baseService.get(roleId);
			modelAndView.addObject("role", role);
		}
		return modelAndView;
	}
	
	/**
	 * 添加用户到角色组
	 */
	@RequestMapping(value = "addRoleUser", method = { RequestMethod.POST, RequestMethod.GET })
	public void addRoleUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String roleId = request.getParameter("roleId");
		String userId = request.getParameter("userId");
		RolesUsers model = new RolesUsers();
		model.setRoleId(roleId);
		model.setUserId(userId);
		if (((RoleService)this.baseService).addUser(model) > 0) {
			renderJson(new JsonResultModel(HttpStatusCode.SUCCESS.getDesc(), "添加用户到角色组操作成功").toSysJsonString(), response);
		} else {
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "添加用户到角色组操作失败").toSysJsonString(), response);
		}
	}

	/**
	 * 从角色组中移除用户
	 */
	@RequestMapping(value = "removeRoleUser", method = { RequestMethod.POST, RequestMethod.GET })
	public void removeRoleUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String roleId = request.getParameter("roleId");
		String userId = request.getParameter("userId");
		RolesUsers model = new RolesUsers();
		model.setRoleId(roleId);
		model.setUserId(userId);
		if (((RoleService)this.baseService).removeUser(model) > 0) {
			renderJson(new JsonResultModel(HttpStatusCode.SUCCESS.getDesc(), "从角色组中移除用户操作成功").toSysJsonString(), response);
			return;
		} else {
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "从角色组中移除用户操作失败").toSysJsonString(), response);
			return;
		}
	}


	/**
	 * 添加角色组权限（ajax）
	 */
	@RequestMapping(value = "addRoleAccess", method = { RequestMethod.POST, RequestMethod.GET })
	public void addRoleAccess(HttpServletRequest request, HttpServletResponse response) {
		String[] items = request.getParameterValues("items[]");
		String roleId = request.getParameter("roleId");
		Collection<Access> models = new ArrayList<Access>();
		for (String item : items) {
			if (item.indexOf("_") > 0) {
				String[] itemStr = item.split("_");
				Access access1 = new Access();// 方法
				access1.setRoleId(roleId);
				access1.setMenuId(itemStr[0]);
				access1.setMenuMethodId(itemStr[1]);
				access1.setStatus(RecordStatus.AVAILABLE);
				access1.setCreateTime(new Date());
				access1.setUpdateTime(new Date());
				models.add(access1);
				Access access = new Access();// 菜单
				access.setRoleId(roleId);
				access.setMenuId(itemStr[0]);
				access.setStatus(RecordStatus.AVAILABLE);
				access.setCreateTime(new Date());
				access.setUpdateTime(new Date());
				models.add(access);
			} else {
				Access access = new Access();
				access.setRoleId(roleId);
				access.setMenuId(item);
				access.setStatus(RecordStatus.AVAILABLE);
				access.setCreateTime(new Date());
				access.setUpdateTime(new Date());
				models.add(access);
			}
		}
		this.accessService.addUserAccessList(models);
		//清除session缓存
//		HttpSession session = request.getSession();
//		session.removeAttribute("accessSessionInfo");
//		session.removeAttribute("accessMenuSessionInfo");
		renderJson(new JsonResultModel(HttpStatusCode.SUCCESS.getDesc(), "权限添加成功").toSysJsonString(), response);
		return;
	}

	/**
	 * 移除角色组权限（ajax）
	 */
	@RequestMapping(value = "removeRoleAccess", method = { RequestMethod.POST, RequestMethod.GET })
	public void removeRoleAccess(HttpServletRequest request, HttpServletResponse response) {
		String[] items = request.getParameterValues("items[]");
		String roleId = request.getParameter("roleId");
		Collection<Access> models = new ArrayList<Access>();
		for (String item : items) {
			Access access = new Access();
			access.setRoleId(roleId);
			if (item.indexOf("_") > 0) {
				String[] itemStr = item.split("_");
				access.setMenuId(itemStr[0]);
				access.setMenuMethodId(itemStr[1]);
			} else {
				access.setMenuId(item);
			}
			access.setStatus(RecordStatus.AVAILABLE);
			List<Access> accesses = this.accessService.findByModel(access, null, null);
			if (accesses != null && accesses.size() > 0) {
				models.add(accesses.get(0));
			}
		}
		this.accessService.deleteUserAccessList(models);
		//清除session缓存
//		HttpSession session = request.getSession();
//		session.removeAttribute("accessSessionInfo");
//		session.removeAttribute("accessMenuSessionInfo");
		renderJson(new JsonResultModel(HttpStatusCode.SUCCESS.getDesc(), "权限移除成功").toSysJsonString(), response);
		return;
	}

}
